package com.gframework.autoconfigure;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.gframework.mybatis.dao.datasource.DynamicDataSourceManager;
import com.gframework.mybatis.dao.datasource.DynamicDataSourceManagerImpl;
import com.gframework.mybatis.dao.datasource.MultipartDataSourceAspect;
import com.gframework.mybatis.dao.datasource.RoutingDataSource;

/**
 * 多数据源 <strong>管理器/DataSource/Aop</strong> 自动装配类.
 * <p>
 * {@link DynamicDataSourceManager}只是一个多数据源管理器，多数据源具体的使用获取注册，均不是此管理器会关注的内容。
 * {@link RoutingDataSource}则是一个真正实现多数据源切换的DataSource接口子类
 * 
 * @since 2.0.0
 * @author Ghwolf
 */
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter({ DataSourceAutoConfiguration.class})
@ConditionalOnBean(DataSourceAutoConfiguration.class)
public class DynamicDataSourceAutoConfiguration implements BeanPostProcessor{

	/**
	 * 多数据源管理器创建
	 */
	@Bean
	public DynamicDataSourceManager getDynamicDataSourceManager() {
		return new DynamicDataSourceManagerImpl();
	}
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof DataSource) {
			return new RoutingDataSource((DataSource) bean);
		} else {
			return bean ;
		}
	}
	
	/**
	 * 多数据源注解切换aop操作对象创建
	 */
	@Bean
	@ConditionalOnBean(DataSource.class)
	public MultipartDataSourceAspect getMultipartDataSourceAspect(){
		return new MultipartDataSourceAspect();
	}

}
